<?php defined('SYSPATH') or die('No direct script access.');
require_once(APPPATH. 'classes/model/Model_Mysql.php');

class Model_UserFeeds extends Model_Mysql {
	const TYPE_WALL = 1;
	const TYPE_PHOTO = 2;
	const TYPE_FRIEND = 3;
	const TYPE_COUPLE = 4;
	
	const ACCESS_PRIVATE = 1;
	const ACCESS_PARTNER = 2;
	const ACCESS_FRIENDS = 3;
	const ACCESS_FR_FRIENDS = 4;
	const ACCESS_EVERYONE = 10;
	
	public function addFeed($uid, $type, $access, $location_id, $text) {
		$sql = "INSERT INTO users_feed(type,access,length,postedby,postedloc,text,time)
				VALUES($type, $access,0,$uid,$location_id,:text,".time().")";
		$query = DB::query(Database::INSERT, $sql)->param(':text', $text);
		try {
			$result = $this->execute($query);
			if($result) {
				$un = new Model_User_Notifications();
				if($uid != $location_id) 
					$un->addNotification($location_id, Model_User_Notifications::FEED, $result[0]);
				return true;
			}
		} catch(Exception $e) {
			throw $e;
			return false;
		}
		return false;
	}
	public function getUserWallFeeds($uid, $access = self::ACCESS_FRIENDS) {
		$sql = "SELECT * FROM users_feed WHERE postedloc=$uid AND access=$access 
				ORDER BY time DESC LIMIT 10";
		$query = DB::query(Database::SELECT, $sql);
		$result = $this->execute($query);
		$feeds = array();
		foreach ($result as $feed) {
			$feeds[$feed['feedid']] = $feed;
		}
		return $feeds;
	}
	public function getStreamFeeds($uids, $access = self::ACCESS_FRIENDS) {
		$sql = "SELECT * FROM users_feed WHERE postedloc in (".implode(",", $uids).
				") AND access=$access ORDER BY time DESC LIMIT 30";
		$query = DB::query(Database::SELECT, $sql);
		$result = $this->execute($query);
		$feeds = array();
		foreach ($result as $feed) {
			$feeds[$feed['feedid']] = $feed;
		}
		return $feeds;
	}
	public function onCommentAdded($feedid, $uid) {
		//"UPDATE users_feed, user_comments set users_feed.length = users_feed.length + 1 WHERE user_comments.cid = 4 AND user_comments.feedid = users_feed.feedid";
		$un = new Model_User_Notifications();
		$un->addByFeed($feedid, array($uid));
		$sql = "UPDATE users_feed SET length = length+1 WHERE feedid = $feedid";
		$query = DB::query(Database::UPDATE, $sql);
		return $this->execute($query);
	}
}